﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            notifyIcon1.Visible = true;
            CheckForIllegalCrossThreadCalls = false;
            dt.Eve += SK_Eve;
            dt.War += SK_wr;
            this.TransparencyKey = Color.Red;
            this.BackColor = Color.Red;
            //  uc.SetLeftCurve("B", new float[] { }, Color.Tomato);
            //textBox1.Text = Properties.Settings.Default.save;
            //value.Text = Properties.Settings.Default.value.ToString();
            this.ShowInTaskbar = false;
            this.TopMost = true;

            InitLv();

            try
            {
                FileStream fs = new FileStream("user.db", FileMode.Open);
                BinaryFormatter bf = new BinaryFormatter();
                sd = (SaveData)bf.Deserialize(fs);
                fs.Close();
            }
            catch 
            {
                sd = new SaveData();
                return;
            }
        }
        private void InitLv()
        {
            dataGridView1.Columns.Add("a", "代码描述");
            dataGridView1.Columns.Add("b", "预警");
            dataGridView1.RowHeadersVisible = false;
            this.dataGridView1.AllowUserToAddRows = false;
            //dataGridView1.Columns[0].Visible = false;
            //dataGridView1.
        }
        Date dt = new Date();
        private void SK_Eve(string str)
        {
            try
            {
                label1.Text = str;
                ss = str;
                SetNotifyIconText(notifyIcon1, str);
            }
            catch 
            {
            }
        }
        private void SK_wr(string str)//弹窗
        {
            Mes(str);
        }
        SaveData sd = new SaveData();
        public static void SetNotifyIconText(NotifyIcon ni, string text)
        {
            if (text.Length >= 256) throw new ArgumentOutOfRangeException("Text limited to 127 characters");
            Type t = typeof(NotifyIcon);
            BindingFlags hidden = BindingFlags.NonPublic | BindingFlags.Instance;
            t.GetField("text", hidden).SetValue(ni, text);
            if ((bool)t.GetField("added", hidden).GetValue(ni))
                t.GetMethod("UpdateIcon", hidden).Invoke(ni, new object[] { true });
        }

        string ss = "";
        //启动
        private void started_Click(object sender, EventArgs e)
        {
            sd.list.Clear();
            sd.value.Clear();
            dt.CodeList = new string[dataGridView1.Rows.Count];
            dt.WarnList = new double[dataGridView1.Rows.Count];

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                string cd=dataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
                string md=dataGridView1.Rows[i].Cells[1].Value.ToString();
                if (cd.Length!=6)
                {
                    dt.CodeList = new string[0];
                    return;
                }
                double f;
                try
                {
                    f=Convert.ToDouble(md);
                }
                catch (Exception)
                {
                    dt.CodeList = new string[0];
                    return;
                }
                dt.CodeList[i] = cd;
                dt.WarnList[i] = f;

                sd.list.Add(cd);
                sd.value.Add(f);
            }

            button1.Enabled = false;
            button1.Visible= false;
            button4.Visible = false;
            dataGridView1.Visible = false;
            add.Visible = false;
            code.Visible = false;
            checkBox1.Visible = false;

            dt.Start();

            try
            {
                FileStream fs = new FileStream("user.db", FileMode.Create);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, sd);
                fs.Close();
            }
            catch 
            {
            }

        }
        //停止
        private void stop_Click(object sender, EventArgs e)
        {
            button1.Enabled = true;
            button1.Visible = true;
            button4.Visible = true;
            dataGridView1.Visible = true;
            add.Visible = true;
            code.Visible = true;
            checkBox1.Visible = true;
            dt.Stop();
        }

        //双击显示
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
        }
        //弹窗通知
        void Mes(string str)
        {
            int tipShowMilliseconds = 200;
            string tipTitle = "";
            ToolTipIcon tipType = ToolTipIcon.Info;
            notifyIcon1.ShowBalloonTip(tipShowMilliseconds, tipTitle, str, tipType);
        }


        //关闭软件
        private void close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //最小化
        private void min_Click(object sender, EventArgs e)
        {
            this.Hide();
        }


//******************************************列表添加***************************************

        //添加
        private void add_Click(object sender, EventArgs e)
        {
            #region //方法一
            int index = dataGridView1.Rows.Add();
            this.dataGridView1.Rows[index].Cells[0].Value = code.Text;
            this.dataGridView1.Rows[index].Cells[1].Value = "5";
            #endregion
        }
        //删除
        private void delete_Click(object sender, EventArgs e)
        {           
            if (this.dataGridView1.CurrentRow != null)
            {
                int t = this.dataGridView1.CurrentRow.Index;
                dataGridView1.Rows.Remove(this.dataGridView1.Rows[t]);
            }
        }


//******************************************鼠标拖动*****************************************

        //鼠标拖动
        Point mouseOff;//鼠标移动位置变量
        bool leftFlag;//标记是否为左键
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseOff = new Point(-e.X, -e.Y); //得到变量的值
                leftFlag = true;         //点击左键按下时标注为true;
            }
        }
        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(mouseOff.X, mouseOff.Y); //设置移动后的位置
                Location = mouseSet;
            }
        }
        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            if (leftFlag)
            {
                leftFlag = false;//释放鼠标后标注为false;
            }
        }

        private void checkBox1_Click(object sender, EventArgs e)
        {
            dt.DispName = checkBox1.Checked;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //数据载入
            try
            {
                for (int i = 0; i < sd.list.Count; i++)
                {
                    DataGridViewRow dgvr = new DataGridViewRow();
                    foreach (DataGridViewColumn c in this.dataGridView1.Columns)
                    {
                        dgvr.Cells.Add(c.CellTemplate.Clone() as DataGridViewCell);
                    }
                    dgvr.Cells[0].Value = sd.list[i];
                    dgvr.Cells[1].Value = sd.value[i].ToString();
                    this.dataGridView1.Rows.Add(dgvr);
                }
            }
            catch
            {
            }

        }
    }

    class Date
    {
        //代码列表
        public string[] CodeList=new string[0];
        //预警数值
        public double[] WarnList=new double[0];

        public bool DispName=true;

        bool[] FlgList=new bool[0];

        //初始化数据
        public Date()
        {
            client.Headers.Add("Content-Type", "text/html; charset=gb2312");

        }
        WebClient client = new WebClient();      
        Stream data;
        StreamReader reader;

        public delegate void eve(string str);
        public event eve Eve;
        public event eve War;
        Thread Th;

        bool RunFlg = false;//运行标志

        //启动
        public void Start()
        {
            FlgList = new bool[WarnList.Length];
            RunFlg = true;
            Th = new Thread(new ThreadStart(ThreadRun));
            Th.IsBackground = true;
            Th.Start();


        }
        //停止
        public void Stop()
        {
            RunFlg = false;
            Thread.Sleep(200);
            if (Th != null && Th.IsAlive)
            {
                Th.Abort();
            }
        }

        //多线程运行
        public void ThreadRun()
        {
            while (RunFlg)
            {
                try
                {
                    string Mes = "";
                    string MesWarm = "";
                    bool wflg = false;
                    Thread.Sleep(700);
                    string[] tmp = GetDate("000001");
                    string name = "";
                    if (DispName)
                    {
                        name = tmp[0];
                    }
                    Mes += name + ":" + pers(tmp) + "\r\n";

                    for (int i = 0; i < CodeList.Length; i++)
                    {
                        tmp = GetDate(CodeList[i]);
                        if (DispName)
                        {
                            name = tmp[0];
                        }
                        if (tmp.Length > 2)
                        {

                            Mes += name + ":" + pers(tmp) + "\r\n";

                            double val = Convert.ToDouble(pers(tmp));
                            if (val >= WarnList[i] && !FlgList[i])//涨破
                            {
                                MesWarm += name + ":" + pers(tmp) + "\r\n";
                                wflg = true;
                                FlgList[i] = true;
                            }
                            if (val < WarnList[i])//涨破
                            {
                                FlgList[i] = false;
                            }
                        }
                    }
                    //结果数据
                    Eve?.Invoke(Mes);
                    //触发提示
                    if (wflg)
                    {
                        War?.Invoke(MesWarm);
                    }
                }
                catch (Exception f)
                {
                   // MessageBox.Show(f.ToString());
                }

            }
        }

        //
        string pers(string[] str)
        {
            double num = Convert.ToDouble(str[2]);
            double num2 = Convert.ToDouble(str[3]);
            double h = (num2 - num) / num * 100.0;
            return h.ToString("f3");
        }

        //结果
        private string[] GetDate(string Number)
        {
            //判断类型、非安全。需要保证6位数字代码。
            string StrType = "";
            if (Number[0]=='6'|| Number == "000001"|| Number[0] == '5')
            {
                StrType = "sh";
            }
            else
            {
                if (Number[0] == '3' || Number[0] == '0'|| Number[0] == '1')
                {
                    StrType = "sz";
                }
                else
                {
                    return new string[0];
                }

            }


            //拉取数据
            try
            {
                data = client.OpenRead("http://hq.sinajs.cn/type=js&list="+ StrType+ Number);
            }
            catch
            {
                return new string[0];
            }          
            reader = new StreamReader(data, Encoding.GetEncoding("gb2312"));
            string s = reader.ReadToEnd();
            reader.Close();
            data.Close();
            return ExtractDate(s).Split(',');
        }   
        //解析数据
        private string ExtractDate(string s)
        {
            char[] d = s.ToCharArray();
            bool isTrue = false;
            string news = "";
            foreach (char newd in d)
            {
                if (isTrue == false)
                {
                    if (newd == '\"')
                    {
                        isTrue = true;
                    }
                }
                else
                {
                    if (newd == '\"')
                    {
                        isTrue = false;
                    }
                    else
                    {
                        news = news + newd;
                    }
                }
            }
            return news;
        }


    }

    [Serializable]
    class SaveData
    {

       public List<string> list = new List<string>();
       public List<double> value = new List<double>();
    }
}
